package com.lcm.weam.controller.sys;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.lcm.weam.entity.resp.PageResult;
import com.lcm.weam.entity.resp.Result;
import com.lcm.weam.entity.resp.ResultCode;
import com.lcm.weam.entity.sys.FileList;
import com.lcm.weam.entity.sys.User;
import com.lcm.weam.service.sys.UserService;
import com.lcm.weam.util.AliOSSUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * 用户模块接口
 * 1、查看所有用户信息
 * 2、根据id/手机号查询用户信息
 * 3、更新用户信息
 * 4、修改用户密码
 * 5、上传用户头像到阿里云
 * 6、上传用户文件到阿里云（我的文件模块）
 * 7、列举用户文件（我的文件模块）
 * 8、下载用户文件（我的文件模块）
 * 9、删除用户文件（我的文件模块）
 * 10、发送验证邮件（权限管理模块）
 * 11、设置验证成功，提升用户权限（权限管理模块、待优化）
 */
@CrossOrigin
@RestController
@RequestMapping(value = "/sys/user")
public class UserController {

    private static final int HASHITERATIONS = 3;

    @Autowired
    private UserService userService;

    /**
     * 1、查看所有用户信息
     * 传递：无
     * 响应：SUCCESS，user列表
     */
    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    public Result selectAll() {
        List<User> users = userService.selectAll();
        return new Result(ResultCode.SUCCESS, users);
    }

    /**
     * 2、根据id查询用户信息
     * 传递：uid
     * 响应：SUCCESS，user
     */
    @RequestMapping(value = "/selectById", method = RequestMethod.GET)
    public Result selectById(@RequestParam(value = "uid", required = true) String uid) {
        User user = userService.selectById(uid);
        return new Result(ResultCode.SUCCESS, user);
    }

    /**
     * 2、根据手机号查询用户信息
     * 传递：mobile
     * 响应：SUCCESS，user
     */
    @RequestMapping(value = "/selectByMobile", method = RequestMethod.GET)
    public Result selectByMobile(@RequestParam(value = "mobile", required = true) String mobile) {
        User user = userService.selectByMobile(mobile);
        return new Result(ResultCode.SUCCESS, user);
    }

    /**
     * 3、更新用户信息
     * 传递：user
     * 响应：SUCCESS
     */
//    @RequiresPermissions(value = {"user-update"})
    @RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
    public Result updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 4、修改用户密码
     */
    @RequestMapping(value = "/{uid}/changePassword", method = RequestMethod.PUT)
    public Result changePassword(@RequestBody Map<String, String> map, @PathVariable String uid) {
        String newPassword = map.get("newPassword"); //用户输入的新密码
        String oldPassword = map.get("oldPassword"); //用户输入的旧密码
        if (!userService.checkPassword(oldPassword, uid)) {
            return new Result(ResultCode.WRONG_PASSWORD_ERROR);
        } //检查旧密码是否输入正确
        if (newPassword.equals(oldPassword)) {
            return new Result(ResultCode.DIFFERENT_PASSWORD_ERROR);
        } //检查新旧是否一致
        userService.changePassword(newPassword, uid);
        return new Result(ResultCode.SUCCESS);
    }

/*    //pageIndex为当前页，pageSize为一页的容积
    @RequestMapping(value = "/selectPageUser", method = RequestMethod.GET)
    public Result selectPageUser(int pageIndex, int pageSize) {
        IPage<User> userIPage = userService.selectPageUser(pageIndex, pageSize);
        return new Result(ResultCode.SUCCESS, new PageResult<User>(userIPage.getTotal(), userIPage.getRecords()));
    }*/

    /**
     * 5、用户上传头像
     * 1、图片url保存在阿里云
     * 2、数据库存放url
     */
    @RequestMapping(value = "/{uid}/uploadPhotoAliOSS", method = RequestMethod.POST)
    public Result uploadPhotoAliOSS(MultipartFile file, @PathVariable String uid) throws IOException {
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image")) {
            System.out.println(contentType);
            return new Result(ResultCode.FAIL, "请上传图片");
        }
        String imgUrl = userService.uploadPhotoAliOSS(uid, file);
        return new Result(ResultCode.SUCCESS, imgUrl);
    }


    /**
     * 6、用户上传文件
     * 1、图片url保存在阿里云
     * 传递：MultipartFile
     */
    @RequestMapping(value = "/{uid}/uploadFileAliOSS", method = RequestMethod.POST)
    public Result uploadFileAliOSS(MultipartFile file, String fileName, @PathVariable String uid) throws IOException {
        userService.uploadFileAliOSS(uid, file, fileName);
        return new Result(ResultCode.SUCCESS);
    }


    /**
     * 7、列举用户文件
     */
    @RequestMapping(value = "/{uid}/listFiles", method = RequestMethod.GET)
    public Result listFiles(int page, int num, @PathVariable String uid) {
        if (page > 0 && num > 0) {
            PageResult<FileList> pageResult = userService.listFiles(uid, page, num);
            return new Result(ResultCode.SUCCESS, pageResult);
        } else {
            return new Result(ResultCode.FAIL);
        }
    }


    /**
     * 8、从阿里云下载文件
     */
    @RequestMapping(value = "{uid}/download", method = RequestMethod.GET)
    public Result download(@PathVariable String uid, String objectName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AliOSSUtil aliOSSUtil = new AliOSSUtil();
        OSS download = aliOSSUtil.download(); //记得关闭
        OSSObject object = download.getObject("weam", uid + "/" + objectName);
        String originName = object.getKey();
        final String userAgent = request.getHeader("USER-AGENT");
        String finalFileName = null;
        if (StringUtils.contains(userAgent, "MSIE") || StringUtils.contains(userAgent, "Trident")) {
            finalFileName = URLEncoder.encode(originName, StandardCharsets.UTF_8);
            System.out.println("适配IE浏览器编码");
        } else if (StringUtils.contains(userAgent, "Mozilla")) {
            finalFileName = URLEncoder.encode(originName, "ISO8859-1");
            System.out.println("适配谷歌、火狐浏览器编码");
        } else {
            finalFileName = URLEncoder.encode(originName, StandardCharsets.UTF_8);
            System.out.println("适配其他浏览器的编码格式");
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;filename=\"" + finalFileName + "\"");

        InputStream istream = object.getObjectContent();
        ServletOutputStream ostream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = istream.read(bytes)) > 0) {
            ostream.write(bytes, 0, len);
        }
        istream.close();
        ostream.close();
        download.shutdown(); //关闭
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 9、从阿里云删除文件
     */
    @RequestMapping(value = "{uid}/delete", method = RequestMethod.DELETE)
    public Result delete(String fileName, @PathVariable String uid) {
        AliOSSUtil aliOSSUtil = new AliOSSUtil();
        String res = aliOSSUtil.detete(uid + "/" + fileName);
        return new Result(ResultCode.SUCCESS, res);
    }

    /**
     * 10、发送验证邮件
     */
    @RequestMapping(value = "{uid}/send", method = RequestMethod.GET)
    public Result send(@PathVariable String uid) {
        //判断用户是否已验证
        User user = userService.selectById(uid);
        Boolean isAuth = user.getIsAuth();
        if (isAuth){
            return new Result(ResultCode.SUCCESS, "用户已验证");
        }
        //获取邮箱、用户名
        String username = user.getUsername();
        String email = user.getEmail();
        try {
            userService.send(username, email, uid);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.SUCCESS,"发送成功");
    }

    /**
     * 11、验证邮件
     */
    @RequestMapping(value = "{uid}/auth",method = RequestMethod.GET)
    public Result auth(@PathVariable String uid){
        //用户点击了链接（可以直接匿名访问，待优化）
        userService.auth(uid);
        return new Result(ResultCode.SUCCESS);
    }
}
